package com.example.provider.filter;

import com.example.api.common.trace.TraceIdUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Activate(group = {CommonConstants.PROVIDER})
public class TraceIdFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(TraceIdFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = RpcContext.getServiceContext().getAttachment(TraceIdUtil.TRACE_ID);
        if (traceId != null) {
            TraceIdUtil.setTraceId(traceId);
            logger.info("Dubbo provider traceId: {}", traceId);
        }
        try {
            return invoker.invoke(invocation);
        } finally {
            TraceIdUtil.clearTraceId();
        }
    }
} 